//
//  OnlineMessageViewController.m
//  SIPphone
//
//  Created by wrt on 13-11-11.
//  Copyright (c) 2013年 wrtsoft. All rights reserved.
//

#import "OnlineMessageViewController.h"
#import "PromptChatDateBase.h"
#import "PromptChatVCViewController.h"
#import "ContactsDateBase.h"
#import "SIPInterface.h"

@interface OnlineMessageViewController ()

@end

@implementation OnlineMessageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"instant message", @"即时信息 Instant Message");
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    PromptChatDateBase *promptChatDB = [PromptChatDateBase sharePromptChatDB];
    
    [promptChatDB readDB];
    [promptChatDB readDBForlist];
    [self.tableView reloadData];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.tableView.rowHeight = 65;
    //有新的未读消息时刷新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newmessageincoming) name:@"NEWUNREADCHATMESSAGE" object:nil];
}

#pragma mark -
#pragma mark tableViewDelegateMethod

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    PromptChatDateBase *promptChatDB = [PromptChatDateBase sharePromptChatDB];
    return promptChatDB.listUserNameArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
//        cell.accessoryType = UITableViewCellAccessoryNone;
        
        UILabel *timelabel = [[UILabel alloc] init];
        timelabel.textColor = [UIColor grayColor];
        timelabel.font = [UIFont systemFontOfSize:10];
        [timelabel setFrame:CGRectMake(220, 48, 100, 15)];
        timelabel.tag = 987654;
        [cell addSubview:timelabel];
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 0, 28, 28)];
        [textField setBorderStyle:UITextBorderStyleNone];
        [textField setEnabled:NO];
        textField.background = [UIImage imageNamed:@"AlbumNewNotify.png"];
        textField.textColor = [UIColor whiteColor];
        textField.textAlignment = 1;
        textField.contentVerticalAlignment = 0;
        textField.font = [UIFont boldSystemFontOfSize:11];
        textField.tag = 567890;
        [cell addSubview:textField];
    }
    
    
    ContactsDateBase *contactsDB = [ContactsDateBase shareContactsDataBase];
    PromptChatDateBase *promptChatDB = [PromptChatDateBase sharePromptChatDB];
    BOOL isHaveMarkName = NO;
    
    cell.textLabel.text = promptChatDB.listUserNameArray[indexPath.row];
    for (int i = 0; i < contactsDB.userNameArray.count ; i++)
    {
        if ([promptChatDB.listUserNameArray[indexPath.row] isEqualToString:contactsDB.userNameArray[i]] && [promptChatDB.listIpPortArray[indexPath.row] isEqualToString:contactsDB.ipPortArray[i]])
        {
            isHaveMarkName = YES;
            cell.textLabel.text = contactsDB.markNameArray[i];
            break;
        }
    }
    if (isHaveMarkName == NO)
    {
        cell.textLabel.text = promptChatDB.listUserNameArray[indexPath.row];
    }
    
    if ([promptChatDB.listIsTextOrImgArray[indexPath.row] isEqualToString:@"Image"])
    {
        if ([promptChatDB.listIsSucceedArray[indexPath.row] isEqualToString:@"成功"])
        {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"[%@]",NSLocalizedString(@"image", @"图像 Image")];
        }
        else
        {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"❗[%@]",NSLocalizedString(@"image", @"图像 Image")];
        }
        
    }
    else
    {
        if ([promptChatDB.listIsSucceedArray[indexPath.row] isEqualToString:@"成功"])
        {
            cell.detailTextLabel.text = promptChatDB.listContentArray[indexPath.row];
        }
        else
        {
            cell.detailTextLabel.text = [NSString stringWithFormat:@"❗%@",promptChatDB.listContentArray[indexPath.row]];
        }
    }
    
    UITextField *textField = (UITextField *)[cell viewWithTag:567890];
    int i = 0;
    i = [promptChatDB countForUnreadWithUserName:promptChatDB.listUserNameArray[indexPath.row] andIpport:promptChatDB.listIpPortArray[indexPath.row]];
    if (i == 0)
    {
        [textField setHidden:YES];
    }
    else if (i > 99)
    {
        [textField setHidden:NO];
        textField.text = [NSString stringWithFormat:@"99"];
    }
    else
    {
        [textField setHidden:NO];
        textField.text = [NSString stringWithFormat:@"%d",i];
    }
    
    
    UILabel *timelabel = (UILabel *)[cell viewWithTag:987654];
    timelabel.text = promptChatDB.listTimeArray[indexPath.row];
    
    [cell.imageView setImage:[UIImage imageNamed:@"app_panel_friendcard_icon.png"]];
    
    return cell;
}

//cell选择后的处理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PromptChatDateBase *promptChatDB = [PromptChatDateBase sharePromptChatDB];
    ContactsDateBase *contactsDB = [ContactsDateBase shareContactsDataBase];
    NSString *tempMarkName = [[NSString alloc] init];
    BOOL isHaveMarkName = NO;
    for (int i = 0; i < contactsDB.userNameArray.count ; i++)
    {
        if ([promptChatDB.listUserNameArray[indexPath.row] isEqualToString:contactsDB.userNameArray[i]] && [promptChatDB.listIpPortArray[indexPath.row] isEqualToString:contactsDB.ipPortArray[i]])
        {
            isHaveMarkName = YES;
            tempMarkName = contactsDB.markNameArray[i];
            break;
        }
    }
    if (isHaveMarkName == NO)
    {
        tempMarkName = promptChatDB.listUserNameArray[indexPath.row];
    }
    
    PromptChatVCViewController *promptChatVC = [[PromptChatVCViewController alloc] initWithUserName:promptChatDB.listUserNameArray[indexPath.row] andIpport:promptChatDB.listIpPortArray[indexPath.row] andMarkName:tempMarkName];
    promptChatVC.titleStr = tempMarkName;
    promptChatVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    
    unsigned long windowId = [interface getChatRoomByUserName:promptChatDB.listUserNameArray[indexPath.row] andIPport:promptChatDB.listIpPortArray[indexPath.row] andPort:@"5060"];
    if (windowId == 0)
    {
        [interface creatChatRoomWithUserName:promptChatDB.listUserNameArray[indexPath.row]];
    }
    else
    {
        [PromptChatDateBase sharePromptChatDB].windowID = windowId;
    }
    
    [promptChatDB updateDBforReadWithUserName:promptChatDB.listUserNameArray[indexPath.row] andIpport:promptChatDB.listIpPortArray[indexPath.row]];
    [self presentModalViewController:promptChatVC animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)newmessageincoming
{
    PromptChatDateBase *promptChatDB = [PromptChatDateBase sharePromptChatDB];
    [promptChatDB readDB];
    [promptChatDB readDBForlist];
    dispatch_async(dispatch_get_main_queue(),^{
        [self.tableView reloadData];
    });
}

//dealloc中取消监听
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NEWUNREADCHATMESSAGE" object:nil];
}
@end
